package com.pan.insist.myabtis;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.Base64Utils;

import java.nio.charset.Charset;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <p>重写mybatis的基础类型来达到加密解密相关字段信息</p>
 *
 * @author aneng huang
 * @since 2020/4/27 9:40 上午
 **/
@Slf4j
public class CryptTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, String paramValue,
                                    JdbcType jdbcType) throws SQLException {
        try {
            // 使用算法加密
        	log.info("加密前: {}", paramValue);
            String s1 = Base64Utils.encodeToString(paramValue.getBytes(Charset.defaultCharset()));
            log.info("加密后: {}", s1);
            preparedStatement.setString(columnIndex, s1);
        } catch (Exception e) {
            // 加密失败之后使用原始的数据
            preparedStatement.setString(columnIndex, paramValue);
        }
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return decrypt(resultSet.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return decrypt(resultSet.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return decrypt(callableStatement.getString(columnIndex));
    }

    /**
     * 解密
     * @param param
     *      需要解密的参数
     * @return 明文
     */
    private String decrypt(String param) {
        try {
            byte[] bytes = Base64Utils.decodeFromString(param);
            return new String(bytes, Charset.defaultCharset());
        } catch (Exception e) {
            // 解密异常使用加密的数据
            return param;
        }
    }
}
